import axios from "axios";
import store from "@/store";
import qs from "qs";
import router from '../router/index'
let pendingRequest = new Map();
const generateKey = (config) => {
  const { method, url } = config;
  return [method, url].join("&");
};
function addPendingRequest(config) {
  if (!config?.headers?.cancel_repeat_request) return;
  // 1、调用 generateKey 方法生成 key
  const requestKey = generateKey(config);
  config.cancelToken =
    config.cancelToken ||
    new axios.CancelToken((cancel) => {
      console.log(cancel);
      if (!pendingRequest.has(requestKey)) {
        pendingRequest.set(requestKey, cancel);
      }
    });
}
function removePendingRequest(config) {
  if (!config?.headers?.cancel_repeat_request) return;
  let requestKey = generateKey(config);
  if (pendingRequest.has(requestKey)) {
    // 如果是重复的请求，则执行对应的cancel函数
    let cancel = pendingRequest.get(requestKey);
    if (cancel) {
      cancel(requestKey);
    }
    // 将前一次重复的请求移除
    pendingRequest.delete(requestKey);
  }
}

// create an axios instance
const service = axios.create({
  baseURL: '', // api 的 base_url
  timeout: 120000, // request timeout
  withCredentials: true,
  
});

function getToken() {
  let user = window.localStorage.getItem("userInfo");
  if (user) {
    let userInfo = JSON.parse(user);
    return userInfo.access_Token 
  }else{
    return ""
  }
}

// request interceptor
service.interceptors.request.use(
    (config) => {
      // if (store.getters.token){
        // if(config.url.includes(window.BASE_CONFIG.CITY_BASE_API)){
        // 县级请求市级接口，带市级token
        // config.headers["access_token"] = getCityToken()
      // }else{
        // 市县请求自己后端接口
        config.headers["accessToken"] = getToken();
      // }
      // }
      removePendingRequest(config);
      // addPendingRequest(config);
      return config;
    },
    (error) => {
      // Do something with request error
      Promise.reject(error);
    }
  );

// response interceptor
service.interceptors.response.use(
    (response) => { 
      const res = response.data;
      if (res.state == 200) {
        return Promise.resolve(response.data);
      }else{
        if (res.message == '登录超时,请重新登录') {
          window.localStorage.clear()
          router.replace('/')
          return
        }
        return Promise.reject(res.message);
      }

    },
    (error) => {
      console.log("error");
      console.log(error.response);
      if (error.response == '登录超时,请重新登录') {
        window.localStorage.clear()
        router.replace('/')
        return
      }
      removePendingRequest(error.config || {});
      if (pendingRequest.get(error.message)) return;
      return Promise.reject(error);
    }
  );
  
  export default service;